﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebMvc.Areas.Sys.Models;
using WebMvc.Controllers;
using WebMvc.Models;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace WebMvc.Areas.Sys.Controllers
{
    [Area("Sys")]
    [Authorize(Roles = "super")]
    public class RoleMenuController : BaseController<RoleMenu>
    {
        public RoleMenuController(EFDbContext context) : base(context)
        {
        }

        //根据角色id获取对应的菜单（功能),使用jstree，注意只能返回string集合
        public IActionResult GetMenusByRole(int roleId)
        {
            var roleMenus = GetEntitysByLambdaAndSort(o => o.RoleId == roleId, OrderLambda, IsASC).ToList();
            var menuIds = from t in roleMenus select t.MenuId.ToString();
            return Json(menuIds.ToList());
        }

        /// <summary>
        /// 更新角色与菜单关联关系
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="roleMenus">角色权限集合</param>
        /// <returns></returns>
        public virtual async System.Threading.Tasks.Task<IActionResult> AddOrModifyMult(int roleId, List<RoleMenu> roleMenus)
        {
            //实现思路为，根据roleId先批量删除现有，再添加
            DeleteEntitysByLambda(o=>o.RoleId==roleId);
            foreach (var rm in roleMenus) {
                await AddEntity(rm);
            }
            
            return Json(new { Result = "Success" });
        }

        /// <summary>
        /// 根据角色Id获取菜单及功能
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<int> GetMenuIdsByRoleId(int roleId)
        {
            var roleMenus = GetEntitysByLambdaAndSort(it => it.RoleId == roleId, o => o.SortIndex, true).ToList();
            var menuIds = from t in roleMenus select t.MenuId;
            return menuIds.ToList();
        }
    }
}
